﻿#region

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using BusinessObjects;

#endregion

namespace FastTrackCabService.AdminPanel
{
    public partial class ConfirmBooking : Page
    {
        private static DateTime _pickupDateTime;

        protected void Page_Load(object sender, EventArgs e)
        {
            int bookingId;
            if (int.TryParse(Request.QueryString["bookingId"], out bookingId))
            {
                if (IsPostBack)
                {
                    tbDelivery.Text = hdnDelivery.Value;
                }
                else
                {
                    string bookingType = BookingBLL.GetBookingType(bookingId);
                    if (bookingType == null)
                    {
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        if (bookingType == "PICK & DROP")
                        {
                            PickAndDropBooking booking = PickAndDropBookingBLL.GetBooking(bookingId);
                            _pickupDateTime = booking.OriginDateTime;
                            dvPickAndDrop.Visible = true;
                            dvPickAndDrop.DataSource = new List<PickAndDropBooking> {booking};
                            dvPickAndDrop.DataBind();

                            LoadSubsidiaries(booking.OriginLocation.DistrictId, booking.OriginLocation.City);
                            LoadSupervisors();

                            ViewState["Car"] = booking.VehicleRequirement.NumberOfCars;
                            ViewState["Van"] = booking.VehicleRequirement.NumberOfVans;
                        }
                        else
                        {
                            PickBooking booking = PickBookingBLL.GetBooking(bookingId);
                            _pickupDateTime = booking.OriginDateTime;
                            dvPick.Visible = true;
                            dvPick.DataSource = new List<PickBooking> {booking};
                            dvPick.DataBind();

                            LoadSubsidiaries(booking.OriginLocation.DistrictId, booking.OriginLocation.City);
                            LoadSupervisors();

                            ViewState["Car"] = booking.VehicleRequirement.NumberOfCars;
                            ViewState["Van"] = booking.VehicleRequirement.NumberOfVans;
                        }

                        LoadDrivers();
                        LoadVehicles();
                    }
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            int numberOfCars = Convert.ToInt32(ViewState["Car"]);
            int numberOfVans = Convert.ToInt32(ViewState["Van"]);
            trCar.Visible = numberOfCars != 0;
            trVan.Visible = numberOfVans != 0;
            tblAddVehicle.Visible = numberOfCars != 0 | numberOfVans != 0;
        }

        private void LoadSubsidiaries(int destrictId, string city)
        {
            ddlSubsidiaries.DataSource =
                SubsidiaryBLL.GetAllSubsidiariesWithName(destrictId);
            ddlSubsidiaries.DataTextField = "BranchName";
            ddlSubsidiaries.DataValueField = "SubsidiaryId";
            ddlSubsidiaries.DataBind();

            foreach (ListItem item in ddlSubsidiaries.Items.Cast<ListItem>().Where(item => item.Text == city))
            {
                item.Selected = true;
                return;
            }
        }

        private void LoadSupervisors()
        {
            List<Supervisor> supervisors = SupervisorBLL.GetAllSupervisors(
                Convert.ToByte(ddlSubsidiaries.SelectedValue), "Bookings supervisor");
            ddlSupervisor.DataSource = supervisors;
            ddlSupervisor.DataTextField = "FirstName";
            ddlSupervisor.DataValueField = "StaffId";
            ddlSupervisor.DataBind();
        }

        private void LoadVehicles()
        {
            if (Convert.ToInt32(ViewState["Car"]) != 0)
            {
                List<Vehicle> vehicles = VehicleBLL.GetAllVehicles(Convert.ToByte(ddlSubsidiaries.SelectedValue), "Car",
                    _pickupDateTime);
                ddlCar.DataSource = vehicles;
                ddlCar.DataTextField = "RegistrationNo";
                ddlCar.DataValueField = "RegistrationNo";
                ddlCar.DataBind();
            }

            if (Convert.ToInt32(ViewState["Van"]) != 0)
            {
                List<Vehicle> vehicles = VehicleBLL.GetAllVehicles(Convert.ToByte(ddlSubsidiaries.SelectedValue), "Van",
                    _pickupDateTime);
                ddlVan.DataSource = vehicles;
                ddlVan.DataTextField = "RegistrationNo";
                ddlVan.DataValueField = "RegistrationNo";
                ddlVan.DataBind();
            }
        }

        private void LoadDrivers()
        {
            List<Driver> drivers = DriverBLL.GetAllDrivers(Convert.ToByte(ddlSubsidiaries.SelectedValue),
                _pickupDateTime);

            ddlCarDriver.DataSource = drivers;
            ddlCarDriver.DataTextField = "FirstName";
            ddlCarDriver.DataValueField = "StaffId";
            ddlCarDriver.DataBind();

            ddlVanDriver.DataSource = drivers;
            ddlVanDriver.DataTextField = "FirstName";
            ddlVanDriver.DataValueField = "StaffId";
            ddlVanDriver.DataBind();
        }

        protected void ddlSubsidiaries_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadSupervisors();
            LoadVehicles();
            LoadDrivers();
        }

        protected void ibCar_OnClick(object sender, ImageClickEventArgs e)
        {
            if (ddlCar.Items.Count == 0 || ddlCarDriver.Items.Count == 0) return;

            LoadVehicleGridView(ddlCar.SelectedValue, "Car", Convert.ToInt32(ddlCarDriver.SelectedValue));

            ViewState["Car"] = Convert.ToInt32(ViewState["Car"]) - 1;
            ddlCar.Items.RemoveAt(ddlCar.SelectedIndex);
            int selectedIndex = ddlCarDriver.SelectedIndex;
            ddlCarDriver.Items.RemoveAt(selectedIndex);
            ddlVanDriver.Items.RemoveAt(selectedIndex);
        }

        protected void ibVan_OnClick(object sender, ImageClickEventArgs e)
        {
            if (ddlVan.Items.Count == 0 || ddlVanDriver.Items.Count == 0) return;

            LoadVehicleGridView(ddlVan.SelectedValue, "Van", Convert.ToInt32(ddlVanDriver.SelectedValue));

            ViewState["Van"] = Convert.ToInt32(ViewState["Van"]) - 1;
            ddlVan.Items.RemoveAt(ddlVan.SelectedIndex);
            int selectedIndex = ddlVanDriver.SelectedIndex;
            ddlCarDriver.Items.RemoveAt(selectedIndex);
            ddlVanDriver.Items.RemoveAt(selectedIndex);
        }

        private void LoadVehicleGridView(string regNo, string type, int staffId)
        {
            DataTable dt;
            if (ViewState["CurrentTable"] != null)
            {
                dt = (DataTable) ViewState["CurrentTable"];
            }
            else
            {
                dt = new DataTable();
                dt.Columns.Add(new DataColumn("RegistrationNo", typeof (string)));
                dt.Columns.Add(new DataColumn("Type", typeof (string)));
                dt.Columns.Add(new DataColumn("StaffId", typeof (int)));
            }

            var dr = dt.NewRow();
            dr["RegistrationNo"] = regNo;
            dr["Type"] = type;
            dr["StaffId"] = staffId;
            dt.Rows.Add(dr);

            ViewState["CurrentTable"] = dt;

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void ibReset_OnClick(object sender, ImageClickEventArgs e)
        {
            Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri);
        }

        protected void ibReject_OnClick(object sender, ImageClickEventArgs e)
        {
            BookingBLL.ChangeStatus(Convert.ToInt32(Request.QueryString["bookingId"]), "Rejected");
            Response.Redirect("Default.aspx");
        }

        protected void ibApproved_OnClick(object sender, ImageClickEventArgs e)
        {
            if (!IsValid) return;
            if (Convert.ToInt32(ViewState["Car"]) == 0 && Convert.ToInt32(ViewState["Van"]) == 0)
            {
                int bookingId = Convert.ToInt32(Request.QueryString["bookingId"]);

                BookingBLL.ApproveBooking(bookingId, Convert.ToInt32(ddlSupervisor.SelectedValue),
                    Convert.ToDateTime(tbDelivery.Text));

                foreach (GridViewRow row in GridView1.Rows)
                {
                    string regNo = row.Cells[0].Text;
                    int driverId = Convert.ToInt32(row.Cells[2].Text);
                    Booking_Vehicle_DriverBLL.AllocateVehicleAndDriver(bookingId, regNo, driverId);
                }

                BookingBLL.SendConfirmationMail(bookingId);

                Response.Redirect("Default.aspx");
            }
            else
            {
                lblError.Visible = true;
            }
        }
    }
}